const sqlite3 = require('sqlite3').verbose();
const path = require('path');
const fs = require('fs');

const dbPath = path.join(process.cwd(), 'data', 'database.sqlite');

// 确保数据目录存在
if (!fs.existsSync(path.dirname(dbPath))) {
  fs.mkdirSync(path.dirname(dbPath), { recursive: true });
}

const db = new sqlite3.Database(dbPath);

console.log('初始化数据库...');

// 创建基本表结构
db.serialize(() => {
  // 创建网站配置表
  db.run(`
    CREATE TABLE IF NOT EXISTS site_config (
      id TEXT PRIMARY KEY DEFAULT 'main',
      title TEXT DEFAULT '机器人创新实验室',
      subtitle TEXT,
      description TEXT DEFAULT '专注于机器人技术研发与创新',
      logo TEXT,
      favicon TEXT,
      contact_info TEXT,
      theme TEXT,
      seo TEXT,
      navigation TEXT,
      footer TEXT,
      analytics TEXT,
      carousel_settings TEXT,
      updated_at TEXT DEFAULT CURRENT_TIMESTAMP
    )
  `);

  // 插入默认配置
  db.run(`
    INSERT OR IGNORE INTO site_config (id, title, description, contact_info, theme, navigation, footer)
    VALUES (
      'main',
      '机器人创新实验室',
      '致力于机器人技术研发与创新，培养优秀的机器人工程师',
      '{"email": "contact@roboticslab.com", "phone": "+86-10-12345678", "address": "某某大学某某楼某某室"}',
      '{"primaryColor": "#3b82f6", "secondaryColor": "#64748b", "backgroundColor": "#ffffff", "textColor": "#1e293b"}',
      '[{"id": "home", "label": "首页", "href": "/"}, {"id": "about", "label": "关于我们", "href": "/about"}, {"id": "members", "label": "团队成员", "href": "/members"}, {"id": "projects", "label": "项目成果", "href": "/projects"}, {"id": "news", "label": "新闻动态", "href": "/news"}, {"id": "recruitment", "label": "加入我们", "href": "/recruitment"}]',
      '{"sections": [{"title": "快速链接", "links": [{"label": "关于我们", "href": "/about"}, {"label": "联系我们", "href": "/contact"}]}], "copyright": "© 2024 机器人创新实验室. All rights reserved."}'
    )
  `, (err) => {
    if (err) {
      console.error('插入默认配置失败:', err);
    } else {
      console.log('默认配置已创建');
    }
  });
});

db.close((err) => {
  if (err) {
    console.error('关闭数据库失败:', err);
  } else {
    console.log('数据库初始化完成');
  }
});